/*
 * @Author: lx 664290587@qq.com
 * @Date: 2025-04-10 15:28:23
 * @LastEditors: lx 664290587@qq.com
 * @LastEditTime: 2025-04-10 15:33:51
 * @FilePath: /umi4_cache_template/src/components/EllipsisTooltip/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Tooltip, TooltipProps } from 'antd';
import classNames from 'classnames';
import _ from 'lodash';
import type { FC } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';

const EllipsisTooltip: FC<{
  text?: React.ReactNode;
  className?: string;
  onClickCallback?: () => void;
  fieldProps?: TooltipProps;
}> = (props: any) => {
  const { text, className, onClickCallback, fieldProps = {}, children } = props;

  const [showTooltip, setShowTooltip] = useState(false);

  const wrapRef = useRef<any>(null);
  const spanRef = useRef<any>(null);

  const throttleClick = _.throttle(() => {
    // 执行回调
    onClickCallback?.();
  }, 100);

  useEffect(() => {
    // 外层包裹元素宽度
    const wrapWidth = wrapRef.current?.getBoundingClientRect()?.width || 0;
    // 实际内容宽度
    const textWidth = spanRef.current?.getBoundingClientRect()?.width || 0;
    setShowTooltip(wrapWidth < textWidth);
  }, [text]);

  return (
    <p
      ref={wrapRef}
      className={classNames(styles.pub_mod_ellipsis_tooltip_p, className || '')}
      onClick={() => {
        throttleClick();
      }}
    >
      {showTooltip ? (
        <Tooltip
          {...fieldProps}
          title={text}
          id="pub_mod_ellipsis_tooltip"
          placement={fieldProps?.placement || 'top'}
        >
          {/* 默认展示的文本和hover显示的文本，可以都使用text； */}
          {/* 如果展示的和tooltip提示的文本不一样，使用组建时可包括展示文本在标签中间，这里判断children */}
          <span className={styles.pub_mod_ellipsis_tooltip_content}>
            {children || text}
          </span>
        </Tooltip>
      ) : (
        <span> {children || text}</span>
      )}

      <span
        ref={spanRef}
        style={{
          position: 'absolute',
          whiteSpace: 'nowrap',
          visibility: 'hidden',
        }}
      >
        {children || text}
      </span>
    </p>
  );
};

export default EllipsisTooltip;
